package com.smyh.UIM;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.smyh.UIM.host.HostUpdateFm;
import com.smyh.UIM.host.param.GPRS_Param;
import com.smyh.UIM.host.param.HardwareParam;
import com.smyh.UIM.host.param.Host101PointFm;
import com.smyh.UIM.host.param.Param_101Activity;
import com.smyh.UIM.host.param.Version_info_Param;
import com.smyh.UIM.host.state.GroupActivity;
import com.smyh.UIM.host.state.HostStateActivity;
import com.smyh.cache.UIM.MainCahce;
import com.smyh.common.MinaClientThread;
import com.smyh.protcol.CMDUtil;
import com.smyh.protcol.host.HostCMDUtil;
import com.smyh.util.HexStrUtil;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;

/**
 * Created by 姜龙 on 2016/7/6.
 */
public class HostFragment extends Fragment  {
    private View view;
    FrameLayout footfm;

    //当前视图：碎片view
    static Fragment currentfm;
    //主机下面：碎片view
    static Fragment group, host, param_101, version, gprs, hard,
            host_101_pointFm,hostUpdateFm;

    /**
     *
     */
    static FragmentManager childFragmentManager;
    /**
     * 连接按钮
     */
    public static ToggleButton connection_btn;
    /**
     * 是否初始化成功
     */
    public static ToggleButton ready_btn;
    /**
     * 主机链路地址
     */
    TextView link_addr;
    Dialog dialog;

    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_host, container, false);

        footfm = (FrameLayout) view.findViewById(R.id.footfm);

        initView();
        initEvent();
        return view;
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.getData().getBoolean("isReady")){
                Toast.makeText(getContext(), "设备初始化成功！", Toast.LENGTH_SHORT).show();
                ready_btn.setChecked(true);
                ready_btn.setBackgroundColor(Color.GREEN);
                link_addr.setText(Param_101Activity.param101Map.get(MainCahce.chooseDeviceAddr).getLinkAddr());
                dialog.dismiss();
            }
            else{
                Toast.makeText(getContext(), "5秒内外设设备没有反应，重新初始化点击旁边初始化单选框！", Toast.LENGTH_SHORT).show();
                ready_btn.setChecked(false);
                dialog.dismiss();
            }
        }
    };
    private void initEvent() {
        ready_btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(!isChecked){
                    ready_btn.setChecked(false);
                    ready_btn.setBackgroundColor(Color.RED);
                    return;
                }else{
                    dialog = CustomDialog.createLoadingDialog(getContext(),"正在Ready,请稍后...");
                }
                final long startTime = System.currentTimeMillis();
                final IoSession session = MinaClientThread.session;
                if (session==null || !session.isConnected()) {
                    Toast.makeText(getContext(), "通讯断开", Toast.LENGTH_SHORT).show();
                    ready_btn.setChecked(false);
                    return;
                }
                if (!connection_btn.isChecked()) {
                    Toast.makeText(getContext(), "亲：你没建立连接", Toast.LENGTH_SHORT).show();
                    ready_btn.setChecked(false);
                    return;
                }
                dialog.show();
                ready_btn.setBackgroundColor(Color.RED);
                IoBuffer sendBuf = HostCMDUtil.initHostCMD();
                session.write(sendBuf);
                session.setAttribute("READ_FIRST", 1);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            int readState = (Integer) session.getAttribute("READ_FIRST");
                            if (readState == 0) {
                                Bundle b = new Bundle();
                                b.putBoolean("isReady",true);
                                Message m = new Message();
                                m.setData(b);
                                handler.sendMessage(m);
                                return;
                            } else {
                                if (System.currentTimeMillis() - startTime >= 5 * 1000) {
                                    Bundle b = new Bundle();
                                    b.putBoolean("isReady",false);
                                    Message m = new Message();
                                    m.setData(b);
                                    handler.sendMessage(m);
                                    return;
                                }
                            }
                        }
                    }
                }) .start();
            }
        });

        connection_btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                IoSession session = MinaClientThread.session;
                if (session==null || !session.isConnected()) {
                    Toast.makeText(getContext(), "通讯断开", Toast.LENGTH_SHORT).show();
                    connection_btn.setChecked(false);
                    return;
                }
                String deviceStr =  MainCahce.chooseDeviceAddr;
                if ("".equals(deviceStr)||deviceStr.contains("--")) {
                    Toast.makeText(getContext(), "亲：你没选中设备！", Toast.LENGTH_SHORT).show();
                    connection_btn.setChecked(false);
                    return;
                }
                byte[] phAddrBytes = HexStrUtil
                        .hexStr2Bytes( MainCahce.chooseDeviceAddr);
                if (isChecked) {
                    //已经选中说明已经建立连接
                    connection_btn.setBackgroundColor(Color.GREEN);
                    session.write(CMDUtil.on_offConnect(phAddrBytes, true));
                    connection_btn.setSelected(false);
                } else {
                    //处于断开模式：
                    session.write(CMDUtil.on_offConnect(phAddrBytes, false));
                    connection_btn.setBackgroundColor(Color.RED);
                    connection_btn.setSelected(true);
                    //修改RF射频设备状态
                    try {
                        Thread.sleep(500);

                    } catch (InterruptedException e2) {
                        // TODO Auto-generated catch block
                        e2.printStackTrace();
                    }
                }
            }
        });


    }

    private void initView() {
        connection_btn = (ToggleButton) view.findViewById(R.id.connection_btn);
        connection_btn.setBackgroundColor(Color.RED);
        ready_btn = (ToggleButton) view.findViewById(R.id.ready_btn);
        ready_btn.setBackgroundColor(Color.RED);
        link_addr = (TextView) view.findViewById(R.id.link_addr);

        group = new GroupActivity();
        host = new HostStateActivity();
        param_101 = new Param_101Activity();
        gprs = new GPRS_Param();
        hard = new HardwareParam();
        version = new Version_info_Param();
        host_101_pointFm = new Host101PointFm();
        hostUpdateFm = new HostUpdateFm();
        currentfm = group;
        childFragmentManager = getChildFragmentManager();
        getChildFragmentManager().beginTransaction().add(R.id.footfm,group)
                .add(R.id.footfm,host).hide(host).add(R.id.footfm,param_101).hide(param_101)
                .add(R.id.footfm,gprs).hide(gprs).add(R.id.footfm,hard).hide(hard)
                .add(R.id.footfm,version).hide(version)
                .add(R.id.footfm,host_101_pointFm).hide(host_101_pointFm)
                .add(R.id.footfm,hostUpdateFm).hide(hostUpdateFm)
                .commit();
    }

    public static void hiddenAll(){
        childFragmentManager.beginTransaction().hide(group).hide(host).hide(param_101).hide(gprs)
                .hide(hard).hide(version).hide(host_101_pointFm).hide(hostUpdateFm).commit();
    }
    public static void showCurrentFM(){
        childFragmentManager.beginTransaction().show(currentfm).commit();
    }

    public static void setCurrentfm(int position) {
        //主机菜单
        switch (position){
            case 0:
                if(currentfm != group){
                    currentfm = group;
                    hiddenAll();
                    showCurrentFM();
                }
                break;
            case 1:
                if(currentfm != host){
                    currentfm = host;
                    hiddenAll();
                    showCurrentFM();
                }
                break;
            case 2:
                if(currentfm != param_101){
                    currentfm = param_101;
                    hiddenAll();
                    showCurrentFM();
                }
                break;
            case 3 :
                if(currentfm != hard){
                    currentfm = hard;
                    hiddenAll();
                    showCurrentFM();
                }
                break;
            case 4:
                if(currentfm != gprs){
                    currentfm = gprs;
                    hiddenAll();
                    showCurrentFM();
                }
                break;
            case 5:
                if(currentfm != version){
                    currentfm = version;
                    hiddenAll();
                    showCurrentFM();
                }
                break;
            case 6:
                if(currentfm != host_101_pointFm){
                    currentfm = host_101_pointFm;
                    hiddenAll();
                    showCurrentFM();
                }
                break;
            case 7:
                if(currentfm != hostUpdateFm){
                    currentfm = hostUpdateFm;
                    hiddenAll();
                    showCurrentFM();
                }
                break;
        }

    }
}
